<html>

<head>
    <title>Canvas tutorial</title>
    <style type="text/css">
        canvas {
            border: 1px solid black;
        }

        .top {
            margin-bottom: 10px;
        }
    </style>
</head>

<body>
    <div class="top">
        <input type="number" id="n" placeholder="边数" value="3">
        <input type="number" id="size" placeholder="边长" value="80">
        <input type="number" id="X" placeholder="x坐标" value="100">
        <input type="number" id="Y" placeholder="y坐标" value="100">
        <button id="confirm">确定</button>
    </div>
    <canvas id="canvas" width="300" height="300"></canvas>
</body>
<script type="text/javascript">
    let canvas = document.getElementById("canvas");
    let ctx = canvas.getContext("2d");

    let confirmBtn = document.getElementById('confirm');
    let n = document.getElementById('n');
    let size = document.getElementById('size');
    let X = document.getElementById('X');
    let Y = document.getElementById('Y');

    confirmBtn.addEventListener('click', () => {
        handleDraw()
    })

    function handleDraw() {
        if (parseInt(size.value) >= 3) {
            drawPolygon()
        } else {
            alert('请输入合法的多边形边数')
        }
    }


    function drawPolygon() {
        console.log(`边数：${n.value}, 边长：${size.value}, X:${X.value}, Y：${Y.value}`)
        let R = size.value / (2 * Math.sin(Math.PI / n.value))
        // let rotateDeg = (2 * Math.PI) / Number(n.value);
        // 注意：尽量不要用这种写法 换成 rotateDeg = (2 / Number(n.value)) * Math.PI);

        ctx.save()
        ctx.translate(X.value, Y.value)

        // 正多边形中心点
        ctx.beginPath();
        ctx.arc(0, 0, 2, 0, 2 * Math.PI);
        ctx.fill();
        ctx.closePath();

        // 设 r为圆的半径，n为圆心角度数，L为圆心角对应弧长
        // L=(r/180)*π*n
        // r=180π*n*L

        // 正多边形外接圆半径：a：为边长 n为边数
        // r = a / (2 * Math.sin(Math.PI/n))

        // n.value    边数
        // size.value 边长
        for (let index = 0; index < n.value; index++) {
            ctx.save()
            ctx.beginPath()
            ctx.strokeStyle = 'red';
            // ctx.rotate((2 / Number(n.value)) * index * Math.PI)
            ctx.moveTo(0, 0)
            ctx.lineTo(R, 0)
            ctx.stroke()
            ctx.fill()
            ctx.closePath()
            ctx.restore()
            console.log('R--->', R)
        }

        ctx.restore()

    }
</script>

</html>